<?php
date_default_timezone_set('America/New_York');
function GetCustomers(){
	$conn = GetConnection();
	return $conn->query('SELECT * FROM Customers');
}

function GetCustomers_Sorted(){
	$conn = GetConnection();
	return $conn->query('SELECT * FROM Customers ORDER BY id DESC');
}

function GetCustomer($id){
	$conn = GetConnection();
	if($id == null)
		die("No Customer could be found. I.D. invalid.");
	$results = $conn->query("SELECT * FROM Customers WHERE id='$id'");
	$row = $results->fetch_assoc();
	$conn->close();
	return $row;
}

function EditCustomer($row){
	$conn = GetConnection();
	$first_name = strip_tags($row['first_name']);
	$last_name = strip_tags($row['last_name']);
	$registered = $row['registered'];
	$verification_code = $row['verification_code'];
	$verified = $row['verified'];
	$Keyword_id = $row['keyword_id'];
	$id = $row['id'];
	if((strlen($first_name) > 0) && (strlen($last_name) > 0))
	{
		$conn->query("UPDATE Customers SET first_name='$first_name', last_name='$last_name',registered='$registered', verification_code ='$verification_code', verified = '$verified', updated_at = CURRENT_TIMESTAMP, Keyword_id = '$Keyword_id' WHERE id = '$id'") or die(mysql_error());
	}
	else
		header("Location: http://cs.newpaltz.edu/~N02432643/%20web-course-2012/final/Customers/edit.php?id=".$id."");
	
	$conn->close();
}
function NewCustomer($row){
	$first_name = strip_tags($row['first_name']);
	$last_name = strip_tags($row['last_name']);
	$verification_code = rand_string(20);
	$verified = 0;
	$Keyword_id = 1;
	
	if((strlen($first_name) > 0) && (strlen($last_name) > 0))
	{
		$conn = GetConnection();
		$date = date("Y-m-d H:i:s");
		$conn->query("INSERT INTO Customers (id,first_name,last_name,registered,verification_code,verified,Keyword_id,updated_at) 
		VALUES ('','$first_name','$last_name','$date','$verification_code','$verified','$Keyword_id','CURRENT_TIMESTAMP')") or die(mysql_error());
			$conn->close();

	}
	else {
			die("You need to enter a Company name.");
	}
}

function DeleteCustomer($id){
		$conn = GetConnection();
		$results = $conn->query("Delete FROM Customers WHERE id=$id");
		header('Location: http://cs.newpaltz.edu/~N02432643/%20web-course-2012/final/Customers/');
}

function rand_string( $length ) {
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	
	$size = strlen( $chars );
	$str = '';
	for( $i = 0; $i < $length; $i++ ) {
		$str .= $chars[ rand( 0, $size - 1 ) ];
	}

	return $str;
}